<?php

namespace App\Http\Middleware;

use Closure;
use Config;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Redis;
use App\Eloqumd\Wf\WfUser;

class checkWfToken
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // 参数token校验
        $token = $request->header('token') ?? '';
        $uid = $request->header('uid') ?? '';

        $error = ['code' => 50000, 'message' => trans('wf.Illegal-Request')];
        $logoutForced = ['code' => -10000, 'message' => trans('wf.Forced-Return')];

        $redisKey = 'wf_' . $uid . '_' . $token;

        // 判空操作
        if (empty($token) || empty($uid)) {
            return Response::json($error);
        }
        // 用户是否存在或过期
        if (!Redis::exists($redisKey)) {
            return Response::json($logoutForced);
        }
        // 虚拟用户接入跳过，真实用户校验（密码被修改-用户被禁用）
        $userData = unserialize(Redis::get($redisKey));
        if (is_numeric($uid) && $uid > 0) {
            $originUserData = WfUser::find($uid)->toArray();
            // 用户被删除，不存在了 || 用户被禁用了 || 密码被修改了
            if (
                empty($originUserData) ||
                $originUserData['status'] == 0 ||
                $originUserData['password'] != simple_encrypt(Redis::get($redisKey . '_ps'), 'D', Config::get('api.pwd_cache'))
            ) {
                return Response::json($logoutForced);
            }
        }

        $response = $next($request);
        // dump($response);exit;
        // 日志记录处理
        // $originalResponse = $response->original;

        // $actionData = app('request')->route()->getAction();
        // $logMessageData = [
        //     'logType' => $originalResponse['type'] ?? 'unknow',
        //     'logMessage' => $originalResponse['logMessage'] ?? '',
        //     'optMessage' => $originalResponse['message'],
        //     'user_real_name' => $userData['nickname'],
        //     'log_k' => 'zhihu',
        //     'log_app' => $actionData['namespace'] ?? '',
        //     'log_controller' => $actionData['controller'] ?? '',
        //     'log_action' => (isset($actionData['controller']) ? explode('@', $actionData['controller'])[1] : '')
        // ];
        // $logMessageData = array_merge($logMessageData, $userData);
        // event(new \App\Events\BrowseLogsEvent($logMessageData));

        return $response;
    }
}
